package com.ruoyi.webActivity.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.utils.DateUtil;
import com.ruoyi.common.utils.ObjUtil;
import com.ruoyi.common.utils.StrUtil;
import com.ruoyi.manage.enterprise.domain.PcProductBaseInfo;
import com.ruoyi.manage.enterprise.domain.PcProductCollection;
import com.ruoyi.manage.enterprise.domain.vo.PcProductBaseInfoVo;
import com.ruoyi.manage.enterprise.service.IPcProductBaseInfoService;
import com.ruoyi.manage.enterprise.service.IPcProductCollectionService;
import com.ruoyi.manage.organization.domain.BizOrganization;
import com.ruoyi.manage.organization.domain.vo.BizOrganizationVo;
import com.ruoyi.manage.organization.service.IBizOrganizationService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * 惠企政策Controller
 *
 * @author ruoyi
 * @date 2025-07-18
 */
@Api(tags = "前端业务控制器")
@RestController
@RequestMapping("/web/finance")
public class webJrjgController extends BaseController {

    @Autowired
    private IBizOrganizationService hbJrjgService;

    @Autowired
    private IPcProductBaseInfoService iHbJrcpService;
    /**
     * 配置表别名 默认空
     */
    private final static String TABLE_PREFIX = StrUtil.initTableAlias(null);


    @GetMapping("/institution/list")
    public TableDataInfo financeInstitutionList(BizOrganizationVo hbJrjg, QueryWrapper<BizOrganization> queryWrapper) {
        if (StrUtil.isNotBlank(hbJrjg.getOrgName())) {
            queryWrapper.like(TABLE_PREFIX + "org_name", hbJrjg.getOrgName());
        }
        if (StrUtil.isNotBlank(hbJrjg.getNationalCode())) {
            queryWrapper.apply("find_in_set({0},national_code)", hbJrjg.getNationalCode());
        }
        if (ObjUtil.isNotNull(hbJrjg.getOrgType())) {
            queryWrapper.eq(TABLE_PREFIX + "org_type", hbJrjg.getOrgType());
        }
        if (StrUtil.isNotBlank(hbJrjg.getIsHot())) {
            queryWrapper.orderByDesc("product_total");
        }
        if (StrUtil.isNotBlank(hbJrjg.getIsActive())) {
            queryWrapper.orderByDesc("docking_total");
        }
        if (hbJrjg.getRecommend() != null) {
            queryWrapper.eq(TABLE_PREFIX + "is_enabled", hbJrjg.getRecommend());
        }
        queryWrapper.orderByDesc(TABLE_PREFIX + "create_time");
        startPage();
        List<BizOrganization> list = hbJrjgService.list(queryWrapper);
        return getDataTable(list);
    }

    /**
     * 获取金融机构详细信息
     */
    @ApiOperation(value = "获取金融机构", notes = "金融机构管理")
    @GetMapping(value = "/institution/{id}")
    public AjaxResult getInstitutionInfo(@PathVariable("id") String id) {
        return AjaxResult.success(hbJrjgService.queryGetById(id));
    }

    @Autowired
    private IPcProductCollectionService iPcProductCollectionService;

    @GetMapping("/product/list")
    public TableDataInfo financeProductList(PcProductBaseInfoVo hbJrcp, QueryWrapper<PcProductBaseInfo> queryWrapper) {
        startPage();
        if (StrUtil.isNotBlank(hbJrcp.getBelongInstitutionName())) {
            queryWrapper.like(TABLE_PREFIX + "institution_name", hbJrcp.getBelongInstitutionName());
        }
        if (StrUtil.isNotBlank(hbJrcp.getProductName())) {
            queryWrapper.like(TABLE_PREFIX + "product_name", hbJrcp.getProductName());
        }
        if (StrUtil.isNotBlank(hbJrcp.getCoverage())) {
            queryWrapper.eq("coverage", hbJrcp.getCoverage());
        }
        if (StrUtil.isNotBlank(hbJrcp.getMainGuaranteeWay())) {
            queryWrapper.eq(TABLE_PREFIX + "main_guarantee_way", hbJrcp.getMainGuaranteeWay());
        }
        if (ObjUtil.isNotNull(hbJrcp.getBeginPublishTime()) && ObjUtil.isNotNull(hbJrcp.getEndPublishTime())) {
            queryWrapper.between(TABLE_PREFIX + "audit_time", DateUtil.beginOfDay(hbJrcp.getBeginPublishTime()), DateUtil.endOfDay(hbJrcp.getEndPublishTime()));
        }
        if (hbJrcp.getDeleted() != null) {
            queryWrapper.eq(TABLE_PREFIX + "deleted", hbJrcp.getDeleted());
        }
        if (StrUtil.isNotBlank(hbJrcp.getAuditMode())) {
            queryWrapper.eq(TABLE_PREFIX + "audit_mode", hbJrcp.getAuditMode());
        }
        if (StrUtil.isNotBlank(hbJrcp.getIsRate()) && "1".equals(hbJrcp.getIsRate())) {
            queryWrapper.orderByDesc("interest_rate_limit_lower");
        }

        if (StrUtil.isNotBlank(hbJrcp.getOrgCode())) {
            queryWrapper.apply("INSTR(belong_institution,{0}) > 0", hbJrcp.getOrgCode());
        }

        if (StrUtil.isNotBlank(hbJrcp.getIsHot()) && "1".equals(hbJrcp.getIsHot())) {
            queryWrapper.orderByDesc("apply_num");
        }
        if (StrUtil.isNotBlank(hbJrcp.getServiceAreaCode())) {
            queryWrapper.apply("find_in_set({0},service_area_code) > 0", hbJrcp.getServiceAreaCode());
        }
        if (ObjUtil.isNotNull(hbJrcp.getLoanTerm())) {
            if (hbJrcp.getLoanTerm() > 0) {
                queryWrapper.le("loan_period_limit_upper", hbJrcp.getLoanTerm());
            } else {
                queryWrapper.gt("loan_period_limit_upper", Math.abs(hbJrcp.getLoanTerm()));
            }
        }
        if (ObjUtil.isNotNull(hbJrcp.getLoanLimit())) {
            if (hbJrcp.getLoanLimit() > 0) {
                queryWrapper.le("amount_limit_upper", hbJrcp.getLoanLimit());
            } else {
                queryWrapper.gt("amount_limit_upper", Math.abs(hbJrcp.getLoanLimit()));
            }
        }
        queryWrapper.eq("enabled", "1");
        queryWrapper.orderByDesc(TABLE_PREFIX + "create_time");
        List<PcProductBaseInfo> list = iHbJrcpService.list(queryWrapper);
        List<Long> collectIds = list.stream().map(m -> m.getId()).collect(Collectors.toList());
        if(collectIds.size() > 0){
            List<PcProductCollection> productCollections = iPcProductCollectionService.lambdaQuery().in(PcProductCollection::getProductId, collectIds).select(PcProductCollection::getCollectStatus, PcProductCollection::getProductId).list();
            list.forEach(m -> {
                Optional<PcProductCollection> productCollection = productCollections.stream().filter(f -> f.getProductId().equals(m.getId())).findFirst();
            if (productCollection.isPresent()) {
                m.setIsCollected(productCollection.get().getCollectStatus());
            } else {
                m.setIsCollected("0");
            }
            });
        }

        return getDataTable(list);
    }

    /**
     * 获取金融产品详细信息
     */
    @ApiOperation(value = "获取金融产品", notes = "金融产品管理")
    @GetMapping(value = "/product/{id}")
    public AjaxResult getProductInfo(@PathVariable("id") Long id) {
        return AjaxResult.success(iHbJrcpService.queryGetById(id));
    }


}
